<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2021/11/18
 * Time: 10:01
 */

namespace app\api\controller\android\v12;


use app\api\model\Capital;
use app\api\model\CapitalValue;
use app\api\model\Detailed;
use app\api\model\DetailedCategory;
use app\api\model\DetailedOption;
use app\api\model\DetailedOptionValue;
use app\api\model\EnvelopeRecords;
use app\api\model\Envelopes;
use app\api\model\KafkaProducer;
use app\api\model\OrderModel;
use app\api\model\VisaForm;
use think\Controller;
use app\api\model\Authority;
use app\api\model\Common;
use think\Request;
use think\Exception;
use app\index\model\Pdf;
use  app\api\model\Approval;
use Think\Db;
use app\api\model\Client;

class NewInfrastructure extends Controller
{
    protected $us;
    protected $pdf;
    
    public function _initialize()
    {
        $this->us  = Authority::check(1);
        $this->pdf = new Pdf();
        
    }
    
    /*
     * 获取配置清单
     */
    public function newDetailedList(DetailedCategory $detailedCategory)
    {
        $data         = Authority::param(['type']);
        $detailedList = $detailedCategory
            ->with(['detailedList', 'detailedList.detailedListValue'])
            ->where('detailed_category.is_enable', 1);
        if ($data['type'] == 0) {
            $detailedList->where('is_agency', 0);
        } else {
            $detailedList->where('is_agency', 1);
        }
        
        $detailedList = $detailedList->order('detailed_category.sort desc')
            ->select();
        foreach ($detailedList as $k => $ite) {
            if (!empty($ite['detailed_list'])) {
                foreach ($ite['detailed_list'] as $l => $value) {
                    $value['title'] = $ite['title'];
                    $value['types'] = 4;
                    if (!empty(array_column($value['detailed_list_value'], 'option_value_title'))) {
                        $value['detailedListValue'] = $value['detailed_title'] . ',' . implode(array_column($value['detailed_list_value'], 'option_value_title'), ',');
                        
                    } else {
                        $value['detailedListValue'] = $value['detailed_title'];
                    }
                    unset($value['detailed_list_value']);
                }
                
            }
            unset($detailedList[$k]['sort'], $detailedList[$k]['is_enable'], $detailedList[$k]['created_at'], $detailedList[$k]['updated_at'], $detailedList[$k]['type'], $detailedList[$k]['is_agency'], $detailedList[$k]['condition']);
        }
        
        r_date($detailedList, 200);
    }
    
    /*
     * 获取报价配置选项
     */
    public function getDetailedOption(DetailedOption $detailedOption)
    {
        $data                   = Authority::param(['id']);
        $getOptionValue['list'] = $detailedOption
            ->with(['detailedListOptionValues' => function ($query) use ($data) {
                $query->where('detailed_option_value.detailed_id', $data['id'])->group('detailed_option_value.option_value_id');
            }])
            ->where('condition', '<>', 2)
            ->order('option_id desc')
            ->select();
        
        foreach ($getOptionValue['list'] as $k => $value) {
            if (!empty($value['detailed_list_option_values'])) {
                $getOptionList['list'][] = $value;
            }
        }
        $getOptionList['PushList'] = db('detailed')
            ->join('detailed_relevance', 'detailed.detailed_id=detailed_relevance.relevance_detailed_id', 'left')
            ->join('detailed_category', 'detailed.detailed_category_id=detailed_category.id', 'left')
            ->field('detailed.detailed_title,detailed.detailed_id,detailed.agency,detailed.detailed_category_id,detailed.artificial,detailed_category.title')
            ->where('detailed_relevance.detailed_id', $data['id'])
            ->where('detailed.display', 1)
            ->select();
        foreach ($getOptionList['PushList'] as $k => $item) {
            $getOptionList['PushList'][$k]['types'] = 4;
        }
        $detailed                 = db('detailed')->join('unit', 'unit.id=detailed.un_id')->where('detailed_id', $data['id'])->field('rmakes,unit.title')->find();
        $getOptionList['remarks'] = $detailed['rmakes'];
        $getOptionList['title']   = $detailed['title'];
        r_date($getOptionList, 200);
    }
    
    /*
     * 报价模版
     */
    public function quotationTemplate()
    {
        $template = db('user_config', config('database.zong'))->where('key', 'quotation_template')->where('status', 1)->value('value');
        r_date(json_decode($template, true), 200);
    }
    
    /*
     * 计算价格
     */
    public function getValuation(DetailedOptionValue $detailedOptionValue, Common $common, Capital $capital)
    {
        $data = Authority::param(['data', 'id', 'types', 'capital_id']);
        if ($data['types'] == 4 || $data['types'] == 1) {
            $detailedValue = $common->newCapitalPrice($detailedOptionValue, $data['id'], json_decode($data['data'], true));
            if (!$detailedValue['code']) {
                r_date([], 300, $detailedValue['msg']);
            }
            $detailedValueList = $detailedValue['data'];
        } else {
            if ($data['types'] == 0) {
                $product_chan               = db('product_chan')->where('product_id', $data['id'])->find();
                $detailedValueList['sum']   = $product_chan['prices'];
                $detailedValueList['price'] = $product_chan['price_rules'];
                $detailedValueList['unit']  = $product_chan['price_rules'];
                
            } elseif ($data['types'] == 2) {
                $capitalIdFind              = $capital->QueryOne($data['capital_id']);
                $detailedValueList['sum']   = $capitalIdFind['un_Price'];
                $detailedValueList['price'] = [];
                $detailedValueList['unit']  = $capitalIdFind['company'];
                
            }
        }
        
        r_date(['price' => $detailedValueList['sum'], 'artificial' => $detailedValueList['price'], 'unTitle' => $detailedValueList['unit']], 200);
    }
    
    /*
     * 基建添加
     */
    public function addInfrastructure(Common $common, Capital $capital, DetailedOptionValue $detailedOptionValue, CapitalValue $capitalValue, OrderModel $orderModel)
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $state = db('order')->where('order_id', $data['order_id'])->value('state');
            $main_mode_type1 = db('sign')->where('order_id', $data['order_id'])->field('autograph,confirm')->find();
            if ($main_mode_type1['confirm'] == 3 && empty($main_mode_type1['autograph'])) {
                db('sign')->where('order_id', $data['order_id'])->delete();
            }
            if(!empty($main_mode_type1['autograph']) && $state==3){
                throw new Exception('合同已签字不允许新增报价');
            }
            $cap = '';
            $orderModel->MultiTableUpdate($data['order_id'], 0);
            if ($data['company']) {
                $op = json_decode($data['company'], true);
                foreach ($op as $ke => $v) {
                    $ValueList = $v['specsList'];
                    if ($v['types'] == 4) {
                        $ValueId      = array_column($ValueList, 'option_value_id');
                        $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $v['product_id'], $ValueId);
                        if (!$CapitalPrice['code']) {
                            throw new Exception($CapitalPrice['msg']);
                        }
                        $CapitalPriceSection      = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $v['fang']);
                        $data['sumMast']          = $CapitalPriceSection[2];
                        $data['sum']              = $CapitalPriceSection[3];
                        $data['price']            = $CapitalPrice['data']['price'];
                        $data['artificial']       = $CapitalPrice['data']['artificial'];
                        $data['categoryTitle']    = $CapitalPrice['data']['categoryTitle'];
                        $data['toPrice']          = $CapitalPriceSection[1];
                        $data['labor_cost_price'] = $CapitalPriceSection[0];
                        $id                       = $capital->newlyAdded($data, $v, 0);
                        foreach ($v['specsList'] as $item) {
                            $capitalValue->Add($item, $id);
                        }
                        
                        if ($v['agency'] == 1) {
                            $p1[] = $CapitalPriceSection[1];
                        } else {
                            $p[] = $CapitalPriceSection[1];
                        }
                    } else {
                        if (!empty($ValueList)) {
                            throw new Exception('请检查参数');
                        }
                        if ($v['types'] == 0) {
                            $product_chan               = db('product_chan')->where('product_id', $v['product_id'])->find();
                            $product_chan['artificial'] = $product_chan['prices'];
                            $product_chan['rmakes']     = $product_chan['price_rules'];
                            $type                       = 0;
                        } elseif ($v['types'] == 1) {
                            $product_chan = db('detailed')->where('detailed_id', $v['product_id'])->find();
                            $type         = 1;
                        } elseif ($v['types'] == 2) {
                            $product_chan['artificial'] = $v['prices'];
                            $product_chan['rmakes']     = isset($v['remarks']) ? $v['remarks'] : '';
                            $type                       = 2;
                        }
                        
                        $id = $capital->oldAdded($product_chan, $v, $data['order_id'], $type, 0);
                        
                        if ($v['agency'] == 1) {
                            $p1[] = $v['fang'] * $v['prices'];
                        } else {
                            $p[] = $v['fang'] * $v['prices'];
                        }
                    }
                    
                    if (!empty($id)) {
                        $cap .= $id . ',';
                        $c   = substr($cap, 0, -1);
                        //交付标准
                        if (isset($v['product_id']) && !empty($v['product_id'])) {
                            $standardId = db('auxiliary_relation')
                                ->join('detailed', 'detailed.detailed_id=auxiliary_relation.serial_id', 'left')
                                ->join('auxiliary_interactive', 'auxiliary_relation.auxiliary_interactive_id=auxiliary_interactive.id', 'left')
                                ->where('detailed.detailed_id', $v['product_id'])
                                ->where('auxiliary_interactive.pro_types', 0)
                                ->column('auxiliary_interactive.id');
                            if (!empty($standardId)) {
                                foreach ($standardId as $item) {
                                    
                                    $auxiliary_interactive  = db('auxiliary_interactive')->where('pro_types', 0)->where('parents_id', $item)->column('id');
                                    $auxiliary_project_list = db('auxiliary_project_list')->insertGetId(['auxiliary_id' => $item, 'capital_id' => $id, 'order_id' => $data['order_id'], 'created_time' => time()]);
                                    foreach ($auxiliary_interactive as $datum) {
                                        if (!empty($datum)) {
                                            db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id' => $datum, 'auxiliary_project_list_id' => $auxiliary_project_list]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            if (config('cityId') == 202) {
                if (isset($p) && !empty($p)) {
                    $o = round(array_sum($p), 2);
                    if ((string)($o * config('give_money')) < $data['give_money']) {
                        throw  new  Exception('主合同优惠金额不能大于主合同订单总价的' . (config('give_money') * 100) . '%');
                    }
                    
                    if ((string)($o * config('expense')) > $data['expense']) {
                        throw  new  Exception('主合同管理费不能小于主合同订单总价的' . (config('expense') * 100) . '%');
                    }
                    
                } else {
                    if ($data['give_money'] != 0) {
                        throw new Exception('主合同没有清单');
                    }
                    if ($data['expense'] != 0) {
                        throw new Exception('主合同没有清单');
                    }
                    
                }
                if (isset($p1) && !empty($p1)) {
                    $o1 = round(array_sum($p1), 2);
                    if ((string)($o1 * config('purchasing_discount')) < $data['purchasing_discount']) {
                        throw  new  Exception('代购优惠金额不能大于代购订单总价的' . (config('purchasing_discount') * 100) . '%');
                    }
                    if ((string)($o1 * config('purchasing_expense')) > $data['purchasing_expense']) {
                        throw  new  Exception('代购管理费不能小于代购订单总价的' . (config('purchasing_expense') * 100) . '%');
                    }
                } else {
                    if ($data['purchasing_discount'] != 0) {
                        throw new Exception('代购合同没有清单');
                    }
                    if ($data['purchasing_expense'] != 0) {
                        throw new Exception('主合同没有清单');
                    }
                    
                }
            }
            $coupon_user_id            = 0;
            $coupon_discount           = 0;
            $purchasing_discount_money = 0;
            $purchasing_id             = 0;
            if (isset($data['couponId']) && !empty($data['couponId'])) {
                $coupon = db('coupon_user', config('database.zong'))->join('coupon', 'coupon_user.coupon_id=coupon.id', 'left')->field('coupon_user.id,coupon.coupon_use_type,coupon.coupon_limit,coupon.coupon_amount,coupon.coupon_type,coupon.coupon_discount,coupon.coupon_prize_title')->whereIn('coupon_user.id', $data['couponId'])->select();
                
                
                foreach ($coupon as $list) {
                    if ($list['coupon_use_type'] == 1) {
                        if (isset($p)) {
                            $o = round(array_sum($p), 2);
                            if ($o < ($list['coupon_limit'] / 100)) {
                                throw new Exception('未达到使用门槛');
                            }
                            if ($list['coupon_type'] == 1) {
                                $coupon_discount += ($list['coupon_amount'] / 100);
                            }
                            
                            if ($list['coupon_type'] == 2) {
                                $coupon_discount += $o * (1 - ($list['coupon_discount'] / 100));
                            }

//                        if ($list['coupon_type'] == 3) {
//                            $data['give_a'] .= $list['coupon_prize_title'] . ',';
//                        }
                            $coupon_user_id = $list['id'];
                        }
                    }
                    if (isset($p1)) {
                        $o1 = round(array_sum($p1), 2);
                        if ($list['coupon_use_type'] == 2) {
                            if ($o1 < ($list['coupon_limit'] / 100)) {
                                throw new Exception('未达到使用门槛');
                            }
                            if ($list['coupon_type'] == 1) {
                                $purchasing_discount_money += ($list['coupon_amount'] / 100);
                            }
                            
                            if ($list['coupon_type'] == 2) {
                                $purchasing_discount_money += $o1 * (1 - ($list['coupon_discount'] / 100));
                            }
                            $purchasing_id = $list['id'];
//                        if ($list['coupon_type'] == 3) {
//                            $data['give_a'] .= $list['coupon_prize_title'] . ',';
//                        }
                        }
                    }
                    
                    
                }
                $data['give_money']          = $data['give_money'] + $coupon_discount;
                $data['purchasing_discount'] = $data['purchasing_discount'] + $purchasing_discount_money;
            }
            $envelopes = db('envelopes')->insertGetId(['wen_a' => $data['wen_a'],//一级分类
                'give_b' => !empty($data['give_a']) ? substr($data['give_a'], 0, -1) : '',
                'ordesr_id' => $data['order_id'],
                'gong' => $data['gong'],
                'give_remarks' => $data['give_remarks'],//备注
                'give_money' => $data['give_money'],//优惠金额
                'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',
                'project_title' => $data['project_title'],
                'expense' => !empty($data['expense']) ? $data['expense'] : 0,
                'purchasing_discount' => $data['purchasing_discount'],
                'purchasing_expense' => !empty($data['purchasing_expense']) ? $data['purchasing_expense'] : 0,
                'type' => 1,
                'created_time' => time(),
                'main_id' => $coupon_user_id,
                'main_discount_money' => round($coupon_discount,2),
                'purchasing_discount_money' =>round($purchasing_discount_money,2),
                'purchasing_id' => $purchasing_id,
            ]);
            if (isset($data['schemeId']) && $data['schemeId'] != 0) {
                db('scheme_use', config('database.zong'))->insert(['plan_id' => $data['schemeId'], 'user_id' => $this->us['user_id'], 'creation_time' => time(), 'city' => config('cityId'), 'order_id' => $data['order_id'], 'envelopes_id' => $envelopes]);
            }
            $capital->whereIn('capital_id', $c)->update(['envelopes_id' => $envelopes]);
            if (!empty($data['give_remarks'])) {
                db('through')->insertGetId(['mode' => '电话', 'amount' => 0, 'role' => 2, 'admin_id' => $this->us['user_id'], 'remar' => $data['give_remarks'], 'order_ids' => $data['order_id'], 'baocun' => 0, 'th_time' => time(), 'end_time' => 0, 'log' => '',//图片
                ]);
            }
            if (!empty($data['Warranty'])) {
                $Warranty = json_decode($data['Warranty'], true);
                foreach ($Warranty as $value) {
                    \db('warranty_collection')->insertGetId(['order_id' => $data['order_id'], 'warranty_id' => $value['warranty_id'], 'years' => $value['years'], 'creation_time' => time(), 'type' => 1, 'envelopes_id' => $envelopes]);
                }
            }
            
            $cap = db('order')->where(['order_id' => $data['order_id']])->field('ification,planned,appointment,telephone')->find();
            if (preg_match("/^1[345678]{1}\d{9}$/", $cap['telephone'])) {
                sendMsg($cap['telephone'], 8615);
            }
            
            db('order')->where(['order_id' => $data['order_id']])->update(['undetermined' => 0, 'ification' => 2, 'agency_address' => isset($data['agency_address']) ? $data['agency_address'] : '', 'order_agency' => isset($p1) && !empty($p1) ? 1 : 0]);
            
            $pdf = $this->pdf->put($data['order_id'], 2, $cap);
            db('user')->where('user_id', $this->us['user_id'])->update(['lat' => $data['lat'], 'lng' => $data['lng']]);
            //页面停留时长
            db('stay')->insertGetId(['startTime' => substr($data['startTime'], 0, -3), 'endTime' => substr($data['endTime'], 0, -3), 'user_id' => $this->us['user_id'], 'order_id' => $data['order_id'], 'time' => time()]);
            //报价及时性
            db('quote')->insertGetId(['startTime' => $cap['appointment'], 'planned' => $cap['planned'], 'user_id' => $this->us['user_id'], 'order_id' => $data['order_id'], 'time' => time()]);
            
            if ($pdf) {
                db()->commit();
//                (new PollingModel())->automatic($data['order_id'], time());
                sendOrder($data['order_id']);
                $clock_in = db('clock_in')->where('order_id', $data['order_id'])->value('order_id');
                if ($clock_in) {
                    $common->toExamine(1, $data['order_id'], 1, '');
                }
                r_date(null, 200);
            }
            
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /**
     * 新版基建报价界面显示
     */
    public function InfrastructureEcho(Envelopes $envelopes)
    {
        $data      = Authority::param(['envelopes_id']);
        $envelopes = $envelopes->with(['CapitalList', 'CapitalList.specsList', 'OrderList'])
            ->where(['envelopes_id' => $data['envelopes_id']])
            ->find();
        
        
        foreach ($envelopes['capital_list'] as $k => $value) {
            $typeCapital ['approval.type'] = 6;
            if ($value['modified_quantity'] != 0) {
                $typeCapital['approval.type'] = array(['=', 6], ['=', 8], 'or');
            }
            $value['username'] = \db('approval', config('database.zong'))
                ->join(config('database.zong')['database'] . '.bi_user', 'approval.nxt_id=bi_user.user_id', 'left')
                ->where($typeCapital)
                ->where('approval.relation_id', $value->capital_id)
                ->order('approval.approval_id desc')
                ->value('bi_user.username');
            
        }
        $capitalList         = $envelopes['capital_list'];
        $c_time              = time();
        $envelopes['coupon'] = null;
        $envelopes['sign']   = \db('sign')->where('order_id', $envelopes['ordesr_id'])->value('autograph');
        if (!empty($envelopes['main_id']) || !empty($envelopes['purchasing_id'])) {
            $id                     = !empty($envelopes['main_id']) ? $envelopes['main_id'] : $envelopes['purchasing_id'];
            $envelopes['coupon']    = db('coupon_user', config('database.zong'))
                ->join('order', 'order.telephone=coupon_user.mobile', 'left')
                ->join('coupon', 'coupon.id=coupon_user.coupon_id', 'left')
                ->where('order.order_id', $envelopes['ordesr_id'])
                ->where('coupon_user.id', $id)
                ->field('coupon_user.id,coupon.coupon_title,(coupon.coupon_limit/100) as coupon_limit,coupon.coupon_use_type,coupon.coupon_type,(coupon.coupon_amount/100) as coupon_amount,coupon.coupon_discount,coupon.coupon_prize_quantity,coupon.coupon_prize_title,coupon.coupon_prize_unit,IF (coupon.coupon_expire_type = 1, coupon.coupon_expire_time_end, coupon_user.create_time + (coupon.coupon_expire_days * 86400)) as coupon_user_expire_e_time')
                ->group('coupon_user.id')
                ->find();
            $envelopes['couponSum'] = $envelopes['main_discount_money'] + $envelopes['purchasing_discount_money'];
            if(empty($envelopes['sign'])){
                if (empty($envelopes['coupon']) || $envelopes['coupon']['coupon_user_expire_e_time'] <= time()) {
        
                    $coupon_user = db('coupon_user', config('database.zong'))->join('coupon', 'coupon.id=coupon_user.coupon_id', 'left')->where('coupon_user.id', $id)->field('coupon.coupon_type,concat(coupon.coupon_prize_title,"x",coupon.coupon_prize_quantity,coupon.coupon_prize_unit) as title')->find();
        
                    $object = ['main_id' => 0, 'main_discount_money' => 0, 'purchasing_discount_money' => 0, 'purchasing_id' => 0, 'give_money' => $envelopes['give_money'] - $envelopes['main_discount_money'] - $envelopes['purchasing_discount_money']];
        
                    if ($coupon_user['coupon_type'] == 3) {
            
                        $give_b = explode(',', $envelopes['give_b']);
                        foreach ($give_b as $l => $o) {
                            if ($o == $coupon_user['title']) {
                                unset($give_b[$l]);
                            }
                        }
                        $object['give_b'] = implode($give_b, ',');
            
                    }
                    $envelopes['couponSum'] = $object['main_discount_money'] + $object['purchasing_discount_money'];
                    db('envelopes')->where(['envelopes_id' => $data['envelopes_id']])->update($object);
                    $envelopes['give_b'] = $object['give_b'];
                   
                }
            }else{
                $envelopes['coupon'] =  db('coupon_user', config('database.zong'))
                    ->join('coupon', 'coupon.id=coupon_user.coupon_id', 'left')
                    ->where('coupon_user.id', $id)
                    ->field('coupon_user.id,coupon.coupon_title,(coupon.coupon_limit/100) as coupon_limit,coupon.coupon_use_type,coupon.coupon_type,(coupon.coupon_amount/100) as coupon_amount,coupon.coupon_discount,coupon.coupon_prize_quantity,coupon.coupon_prize_title,coupon.coupon_prize_unit,IF (coupon.coupon_expire_type = 1, coupon.coupon_expire_time_end, coupon_user.create_time + (coupon.coupon_expire_days * 86400)) as coupon_user_expire_e_time')
                    ->group('coupon_user.id')
                    ->find();
            }
           
            
        }


//        $capital_id  = array_column($capitalList, 'capital_id');
//        $po          = db('auxiliary_project_list')->whereIn('capital_id', $capital_id)->whereNull('delete_time')->field('auxiliary_id,id,capital_id')->select();
//
//        $auxiliary_id          = array_column($po, 'auxiliary_id');
//        $auxiliary_interactive = [];
//        if (!empty($auxiliary_id)) {
//            $auxiliary_interactive = db('auxiliary_interactive')->whereIn('id', $auxiliary_id)->field('id,title')->select();
//        }
//        $id                       = array_column($po, 'id');
//        $auxiliaryInteractiveList = db('auxiliary_interactive')
//            ->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.auxiliary_interactive_id=auxiliary_interactive.id', 'left')
//            ->whereIn('auxiliary_delivery_schedule.auxiliary_project_list_id', $id)
//            ->whereNull('auxiliary_delivery_schedule.delete_time')
//            ->field('auxiliary_interactive.id, auxiliary_interactive.title, auxiliary_delivery_schedule.id as auxiliary_delivery_schedule_id,auxiliary_delivery_schedule.auxiliary_project_list_id')->select();
//        if (!empty($auxiliaryInteractiveList)) {
//            $auxiliary_delivery_node = db('auxiliary_delivery_node')->whereIn('auxiliary_delivery_schedul_id', array_column($auxiliaryInteractiveList, 'auxiliary_delivery_schedule_id'))->field('state,node_id,auxiliary_delivery_schedul_id')->select();
//        }
        $capitalListArray = [];
        $agency           = [];
        $sumlist          = [];
        foreach ($capitalList as $k => $item) {
            if ($item['agency'] == 1) {
                $agency[] = $item;
            } else {
                $sumlist[] = $item;
            }
//            $auxiliary_ids = array_unique(array_column($po, 'id'));
//            if ($po) {
//                foreach ($po as $l => $key) {
//                    if ($item['capital_id'] == $key['capital_id']) {
//                        $capitalListArray[$k]['class_b']       = $item['projectTitle'];
//                        $capitalListArray[$k]['auxiliary_id']  = $item['projectId'];
//                        $capitalListArray[$k]['auxiliary_ids'] = implode($auxiliary_ids, ',');;
//                        foreach ($auxiliary_interactive as $val) {
//                            if ($key['auxiliary_id'] == $val['id']) {
//                                $auxiliaryList[] = $val;
//                            }
//
//                        }
//                        foreach ($auxiliaryList as $ls) {
//                            $auxiliaryInteractiveListNode = [];
//
//                            foreach ($auxiliaryInteractiveList as $p => $value) {
//                                if ($key['id'] == $value['auxiliary_project_list_id'] && $key['id'] == $value['auxiliary_project_list_id']) {
//                                    $state   = 3;
//                                    $node_id = 0;
//                                    foreach ($auxiliary_delivery_node as $node) {
//                                        if ($node['auxiliary_delivery_schedul_id'] == $value['auxiliary_delivery_schedule_id'] && $key['id'] == $value['auxiliary_project_list_id']) {
//                                            $auxiliaryNodeId   = array_column($auxiliary_delivery_node, 'state');
//                                            $auxiliaryNodeNode = array_column($auxiliary_delivery_node, 'node_id');
//                                            if ($auxiliaryNodeId) {
//                                                if (in_array(2, $auxiliaryNodeId)) {
//                                                    $state   = 2;
//                                                    $node_id = implode(',', $auxiliaryNodeNode);
//                                                } elseif (in_array(0, $auxiliaryNodeId)) {
//                                                    $state   = 0;
//                                                    $node_id = implode(',', $auxiliaryNodeNode);
//                                                } else {
//                                                    $state   = 1;
//                                                    $node_id = implode(',', $auxiliaryNodeNode);
//                                                }
//                                            } else {
//                                                $state   = 3;
//                                                $node_id = 0;
//                                            }
//                                        }
//                                    }
//                                    $auxiliaryInteractiveListNode[$p]['state']                          = $state;
//                                    $auxiliaryInteractiveListNode[$p]['node_id']                        = $node_id;
//                                    $auxiliaryInteractiveListNode[$p]['id']                             = $value['id'];
//                                    $auxiliaryInteractiveListNode[$p]['title']                          = $value['title'];
//                                    $auxiliaryInteractiveListNode[$p]['auxiliary_delivery_schedule_id'] = $value['auxiliary_delivery_schedule_id'];
//                                    $auxiliaryInteractiveListNode[$p]['auxiliary_project_list_id']      = $value['auxiliary_project_list_id'];
//                                }
//
//                                $ls['data'] = array_merge($auxiliaryInteractiveListNode);
//                            }
//
//                        }
//                        $capitalListArray[$k]['data'][] = $ls;
//                    }
//                }
//
//            }
            
        }
        
        $result   = array();
        $tageList = [];
        foreach ($envelopes['capital_list'] as $k => $v) {
            $v['specsList'] = $v['specs_list'];
            unset($v['specs_list']);
            $result[$v['categoryName']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['title'] = $k;
            $schemeTag['data']  = $result[$k];
            $tageList[]         = $schemeTag;
        }
        unset($envelopes['capital_list']);
        $envelopes['capital_list'] = $tageList;
        if (!empty($envelopes['give_b'])) {
            $envelopes['give_b'] = explode(',', $envelopes['give_b']);
        } else {
            $envelopes['give_b'] = null;
        }
//        if ($envelopes['capitalgo']) {
//            $envelopes['capitalgo'] = unserialize($envelopes['capitalgo']);
//        } else {
        $envelopes['capitalgo']           = null;
        $envelopes['give_money']          =round($envelopes['give_money'] - $envelopes['main_discount_money'],2);
        $envelopes['purchasing_discount'] = round($envelopes['purchasing_discount'] - $envelopes['purchasing_discount_money'],2);
//        }
        //质保卡
        $warranty_collection = \db('warranty_collection')->where('warranty_collection.envelopes_id', $envelopes['envelopes_id'])->where('warranty_collection.pro_types', 0)->join('warranty', 'warranty.id=warranty_collection.warranty_id', 'left')->where('warranty_collection.order_id', $envelopes['ordesr_id'])->field('warranty.title,warranty_collection.years,warranty_collection.type,warranty_collection.warranty_id,warranty_collection.id')->select();
        
        
        $envelopes['agencysum'] = round(array_sum(array_column($agency, 'allMoney')), 2);
        $envelopes['sumlist']   = round(array_sum(array_column($sumlist, 'allMoney')), 2);
        if($envelopes['sumlist']==0){
            $envelopes['coupon']=null;
        }
        if($envelopes['agencysum']==0){
            $envelopes['coupon']=null;
        }
        
        
        r_date(['company' => $envelopes, 'warranty_collection' => $warranty_collection, 'capitalList' => array_merge($capitalListArray)], 200);
    }
    
    
    /**
     * 成交前基检删除
     */
    public function DeleteBeforeClosing(Capital $capital, OrderModel $orderModel, Envelopes $envelopes)
    {
        $data = Authority::param(['capital_id']);
        db()->startTrans();
        try {
            if ($data['capital_id'] == 0) {
                throw  new  Exception('清单id错误');
            }
            $capitalFind     = $capital->QueryOne($data['capital_id']);
            $capitalAllCount = $capital->whetherAgency(['ordesr_id' => $capitalFind['ordesr_id'], 'types' => 1, 'envelopes_id' => $capitalFind['envelopes_id']]);
            
            $amount = $capital->where(['ordesr_id' => $capitalFind['ordesr_id'], 'types' => 1, 'capital_id' => $data['capital_id']])->field('sum(if(agency=1,to_price,0)) as agentSum,sum(if(agency=0,to_price,0)) as Sum')->select();
            $this->CouponCalculation($capitalFind['envelopes_id'], $amount[0]['Sum'], $amount[0]['agentSum'], 1);
            if ($capitalAllCount == 1) {
                throw  new  Exception('不允许删除,必须保留一个清单');
            }
            $capitalUpdate = ['capital_id' => $data['capital_id'], 'types' => 2, 'untime' => time()];
            $capital->isUpdate(true)->save($capitalUpdate);
            $capital->share($capitalFind['ordesr_id'], $capitalFind['envelopes_id']);
            $main_mode_type1 = db('sign')->where('order_id', $capitalFind['ordesr_id'])->field('autograph,confirm')->find();
            if ($main_mode_type1['confirm'] == 3 && empty($main_mode_type1['autograph'])) {
                db('sign')->where('order_id', $capitalFind['ordesr_id'])->delete();
            }
            $state = db('order')->where('order_id', $capitalFind['ordesr_id'])->value('state');
            if(!empty($main_mode_type1['autograph']) && $state==3){
                throw new Exception('合同已签字不允许删除');
            }
            db()->commit();
            $capitals = $capital->whetherAgency(['ordesr_id' => $capitalFind['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1]);
            if ($capitals > 0) {
                $listOrderType = 1;
            } else {
                $listOrderType = 0;
                $envelopes->isUpdate(true)->save(['envelopes_id' => $capitalFind['envelopes_id'], 'purchasing_discount' => 0, 'purchasing_expense' => 0]);
            }
            $capitals = $capital->whetherAgency(['ordesr_id' => $capitalFind['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 0]);
            if ($capitals == 0) {
                $envelopes->isUpdate(true)->save(['envelopes_id' => $capitalFind['envelopes_id'], 'expense' => 0, 'give_money' => 0]);
            }
            $orderModel->orderAgency(['order_id' => $capitalFind['ordesr_id'], 'order_agency' => $listOrderType]);
            $this->pdf->put($capitalFind['ordesr_id'], 1, 0);
            sendOrder($capitalFind['ordesr_id']);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /**
     * 成交删除分组
     */
    public function DeleteBeforeClosingGrouping(Capital $capital, OrderModel $orderModel, Envelopes $envelopes)
    {
        $data = Authority::param(['categoryName', 'envelopes_id', 'orderId']);
        
        db()->startTrans();
        try {
            
            $state = $orderModel->where(['order_id' => $data['orderId']])->value('state');
            if ($state > 3 && $state <= 7) {
                throw  new  Exception('不允许批量删除');
            }
            $capitalAllCount = $capital->where(['ordesr_id' => $data['orderId'], 'types' => 1, 'envelopes_id' => $data['envelopes_id']])->group('categoryName')->count();
            
            if ($capitalAllCount == 1) {
                throw  new  Exception('不允许删除,必须保留一个清单');
            }
            
            $capital->where(['categoryName' => $data['categoryName'], 'ordesr_id' => $data['orderId'], 'envelopes_id' => $data['envelopes_id']])->update(['types' => 2, 'untime' => time()]);
            
            $capital->share($data['orderId'], $data['envelopes_id']);
            $main_mode_type1 = db('sign')->where('order_id', $data['orderId'])->field('autograph,confirm')->find();
            if (empty($main_mode_type1)) {
                $amount = $capital->where(['categoryName' => $data['categoryName'], 'ordesr_id' => $data['orderId'], 'envelopes_id' => $data['envelopes_id']])->field('sum(if(agency=1,to_price,0)) as agentSum,sum(if(agency=0,to_price,0)) as Sum')->select();
                $this->CouponCalculation($data['envelopes_id'], $amount[0]['Sum'], $amount[0]['agentSum'], 1);
            }
            if(!empty($main_mode_type1['autograph']) && $state==3){
                throw new Exception('合同已签字不允许删除');
            }
            if ($main_mode_type1['confirm'] == 3 && empty($main_mode_type1['autograph'])) {
                db('sign')->where('order_id', $data['orderId'])->delete();
            }
            
            db()->commit();
            $capitals = $capital->whetherAgency(['ordesr_id' => $data['orderId'], 'types' => 1, 'enable' => 1, 'agency' => 1]);
            if ($capitals > 0) {
                $listOrderType = 1;
            } else {
                $listOrderType = 0;
                $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'purchasing_discount' => 0, 'purchasing_expense' => 0]);
            }
            $capitals = $capital->whetherAgency(['ordesr_id' => $data['orderId'], 'types' => 1, 'enable' => 1, 'agency' => 0]);
            if ($capitals == 0) {
                $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'expense' => 0, 'give_money' => 0]);
            }
            $orderModel->orderAgency(['order_id' => $data['orderId'], 'order_agency' => $listOrderType]);
            $this->pdf->put($data['orderId'], 1, 0);
            sendOrder($data['orderId']);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /**
     * 成交后基检删除
     */
    public function TransactionDeletion(Approval $approval, Capital $capital)
    {
        $data = Authority::param(['capital_id', 'quantity', 'reasonForDeduction']);
        db()->startTrans();
        try {
            $capitalFind = $capital->QueryOne($data['capital_id']);
            if ($capitalFind['acceptance'] != 0) {
                throw  new  Exception('该项目已验收不允许删除');
            }
            $personal_price = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $capitalFind['ordesr_id'])->whereNull('deleted_at')->sum('personal_price');
            $orderCapital   = Db::connect(config('database.zong'))->table('large_reimbursement')->where('order_id', $capitalFind['ordesr_id'])->where('status', 1)->sum('money');
            if ($personal_price < $orderCapital) {
                throw  new  Exception('不允许删除：大工地结算金额加过审大工地结算金额超过清单工资');
            }
            $reimbursement = db('reimbursement_relation')->join('reimbursement', 'reimbursement.id=reimbursement_relation.reimbursement_id')->where(['reimbursement_relation.capital_id' => $data['capital_id']])->field('reimbursement.status,reimbursement.order_id')->find();
            if (!empty($reimbursement)) {
                if ($reimbursement['status'] == 1 || $reimbursement['status'] == 0) {
                    throw  new  Exception('该代购主材已提交审批不能删除');
                }
            }
            if (isset($data['quantity']) && $data['quantity'] != 0) {
                $title        = $capitalFind['class_b'] . '减少方量到(' . $data['quantity'] . ')';
                $signed       = 1;
                $approvalType = 9;
            } else {
                $title        = $capitalFind['class_b'] . '项目减项(' . $this->us['username'] . ')';
                $signed       = 0;
                $approvalType = 6;
            }
            $work_time = Db::connect(config('database.db2'))->table('app_user_order_capital')->whereNull('deleted_at')->where('capital_id', $data['capital_id'])->value('work_time');
            if ($work_time != 0) {
                throw  new  Exception('师傅工时不为0无法删除');
            }
            $capitalUpdate = ['approve' => 3, 'modified_quantity' => $data['quantity'], 'reason_for_deduction' => $data['reasonForDeduction'], 'capital_id' => $data['capital_id'], 'signed' => $signed];
            $capital->isUpdate(true)->save($capitalUpdate);
            db()->commit();
            $this->inspect($capitalFind['ordesr_id'], $capitalFind['envelopes_id']);
            $approval->Reimbursement($data['capital_id'], $title, $this->us['username'], $approvalType);
            sendOrder($capitalFind['ordesr_id']);
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /**
     * 基检编辑
     */
    public function QuotationEditing(Common $common, Capital $capital, DetailedOptionValue $detailedOptionValue, CapitalValue $capitalValue, Detailed $detailed, OrderModel $orderModel)
    {
        $data = Authority::param(['capital_id', 'allMoney', 'fang', 'sectionTitle', 'unit', 'price', 'specsList', 'product_id', 'type', 'types', 'categoryName', 'projectTitle', 'agency', 'zhi', 'order_id', 'envelopes_id']);
        db()->startTrans();
        try {
            $ValueList = json_decode($data['specsList'], true);
            $agentSum  = 0;
            $Sum       = 0;
            if ($data['types'] == 4) {
                
                $ValueId      = array_column($ValueList, 'option_value_id');
                $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $data['product_id'], $ValueId);
                if (!$CapitalPrice['code']) {
                    throw new Exception($CapitalPrice['msg']);
                }
                
                $CapitalPriceSection      = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $data['fang']);
                $data['sumMast']          = $CapitalPriceSection[2];
                $data['sum']              = $CapitalPriceSection[3];
                $data['price']            = $CapitalPrice['data']['price'];
                $data['artificial']       = $CapitalPrice['data']['artificial'];
                $data['categoryTitle']    = $CapitalPrice['data']['categoryTitle'];
                $data['toPrice']          = $CapitalPriceSection[1];
                $data['labor_cost_price'] = $CapitalPriceSection[0];
                $data['categoryTitle']    = $detailed->detailedCategoryTitle($data['product_id'])['title'];
                
                if ($data['agency'] == 1) {
                    $agentSum = $CapitalPriceSection[1];
                }
                if ($data['agency'] == 0) {
                    $Sum = $CapitalPriceSection[1];
                }
                $id = $capital->newlyAdded($data, $data, 0);
                
                $list = $capitalValue->where('capital_id', $id)->find();
                if (!empty($list)) {
                    $capitalValue->where('capital_id', $id)->delete();
                }
                
                foreach ($ValueList as $item) {
                    $capitalValue->Add($item, $id);
                }
            } else {
                if (!empty($ValueList)) {
                    throw new Exception('请检查参数' . $data['types']);
                }
                if ($data['types'] == 0) {
                    $product_chan = db('product_chan')->where('product_id', $data['product_id'])->find();
                    $type         = 0;
                } elseif ($data['types'] == 1) {
                    $product_chan = db('detailed')->where('detailed_id', $data['product_id'])->find();
                    $type         = 1;
                } elseif ($data['types'] == 2) {
                    $product_chan['artificial'] = $data['price'];
                    $product_chan['rmakes']     = isset($data['remarks']) ? $data['remarks'] : '';
                    $type                       = 2;
                }
                if ($data['agency'] == 1) {
                    $agentSum = round($product_chan['artificial'] * $data['fang'], 2);
                }
                if ($data['agency'] == 1) {
                    $Sum = round($product_chan['artificial'] * $data['fang'], 2);
                }
                $capital->oldAdded($product_chan, $data, $data['order_id'], $type, 0);
                $id = 0;
                
            }
            
            $main_mode_type1 = db('sign')->where('order_id', $data['order_id'])->field('autograph,confirm')->find();
            $state           = db('order')->where('order_id', $data['order_id'])->value('state');
            if ($state < 4) {
                $types = 0;
                if (!empty($data['capital_id'])) {
                    $types = 1;
                }
                $this->CouponCalculation($data['envelopes_id'], $Sum, $agentSum, $types, $data['capital_id']);
                
            }
            if ($main_mode_type1['confirm'] == 3 && empty($main_mode_type1['autograph'])) {
                db('sign')->where('order_id', $data['order_id'])->delete();
            }
            if(!empty($main_mode_type1['autograph']) && $state==3){
                throw new Exception('合同已签字不允许编辑');
            }
            db()->commit();
            $this->pdf->put($data['order_id'], 1, 0);
            sendOrder($data['order_id']);
            r_date($id, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /**
     * 基检增项
     */
    public function AdditionalItem(Common $common, Capital $capital, DetailedOptionValue $detailedOptionValue, CapitalValue $capitalValue, Envelopes $envelopes, VisaForm $visaForm, EnvelopeRecords $envelopeRecords)
    {
        $data = Authority::param(['company', 'order_id', 'envelopes_id', 'gong']);
        db()->startTrans();
        try {
            if ($data['company']) {
                $ids = [];
                $op  = json_decode($data['company'], true);
                
                foreach ($op as $ke => $v) {
                    
                    if (!empty($v['data'])) {
                        foreach ($v['data'] as $value) {
                            if (!isset($value['specsList'])) {
                                throw new Exception('请编辑清单包后提交');
                            }
                            $ValueList = $value['specsList'];
                            
                            $value['fang']         = $value['square'];
                            $value['categoryName'] = $v['title'];
                            $value['product_id']   = $value['projectId'];
                            $value['unit']         = $value['company'];
                            $value['zhi']          = 1;
                            $value['type']         = 0;
                            $value['envelopes_id'] = $data['envelopes_id'];
                            if ($value['types'] == 4) {
                                $ValueId      = array_column($ValueList, 'option_value_id');
                                $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $value['product_id'], $ValueId);
                                if (!$CapitalPrice['code']) {
                                    throw new Exception($CapitalPrice['msg']);
                                }
                                $CapitalPriceSection = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $value['fang']);
                                
                                $data['sumMast']          = $CapitalPriceSection[2];
                                $data['sum']              = $CapitalPriceSection[3];
                                $data['price']            = $CapitalPrice['data']['price'];
                                $data['artificial']       = $CapitalPrice['data']['artificial'];
                                $data['categoryTitle']    = $CapitalPrice['data']['categoryTitle'];
                                $data['toPrice']          = $CapitalPriceSection[1];
                                $data['labor_cost_price'] = $CapitalPriceSection[0];
                                $id                       = $capital->newlyAdded($data, $value, 1);
                                
                                foreach ($ValueList as $item) {
                                    $capitalValue->Add($item, $id);
                                }
                                
                                if ($value['agency'] == 1) {
                                    $p1[] = $CapitalPriceSection[1];
                                } else {
                                    $p[] = $CapitalPriceSection[1];
                                }
                                
                            } else {
                                if ($value['types'] == 0) {
                                    $product_chan = db('product_chan')->where('product_id', $value['product_id'])->find();
                                    $type         = 0;
                                } elseif ($value['types'] == 1) {
                                    $product_chan = db('detailed')->where('detailed_id', $value['product_id'])->find();
                                    $type         = 1;
                                } elseif ($value['types'] == 2) {
                                    $product_chan['artificial'] = $value['price'];
                                    $product_chan['rmakes']     = isset($value['remarks']) ? $value['remarks'] : '';
                                    $type                       = 2;
                                }
                                $id = $capital->oldAdded($product_chan, $value, $data['order_id'], $type, 1);
                            }
                            
                            $ids[] = $id;
                        }
                        
                        if (isset($value['product_id']) && !empty($value['product_id'])) {
                            
                            $standardId = db('auxiliary_relation')
                                ->join('detailed', 'detailed.detailed_id=auxiliary_relation.serial_id', 'left')
                                ->join('auxiliary_interactive', 'auxiliary_relation.auxiliary_interactive_id=auxiliary_interactive.id', 'left')
                                ->where('detailed.detailed_id', $value['product_id'])
                                ->where('auxiliary_interactive.pro_types', 0)
                                ->column('auxiliary_interactive.id');
                            if (!empty($standardId)) {
                                foreach ($standardId as $item) {
                                    
                                    $auxiliary_interactive  = db('auxiliary_interactive') ->where('pro_types', 0)->where('parents_id', $item)->column('id');
                                    $auxiliary_project_list = db('auxiliary_project_list')->insertGetId(['auxiliary_id' => $item, 'capital_id' => $id, 'order_id' => $data['order_id'], 'created_time' => time()]);
                                    foreach ($auxiliary_interactive as $datum) {
                                        if (!empty($datum)) {
                                            db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id' => $datum, 'auxiliary_project_list_id' => $auxiliary_project_list]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    
                }
                
            }
            
            $capital_id = $capital->where('ordesr_id', $data['order_id'])->where('capital.signed', 0)->where('capital.enable', 1)->where(function ($query) {
                $query->where('capital.types=2')->whereOr('capital.increment=1');
            })
                ->column('capital_id');
            $visaForm->addList($data['order_id'], $capital_id);
            if ($data['gong'] != 0) {
                $envelopesFind = $envelopes->getFind($data['envelopes_id']);
                $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'gong' => $data['gong'] + $envelopesFind['gong']]);
                $array = [];
                array_push($array, [
                        'previous_quantity' => $envelopesFind['gong'],
                        'post_quantity' => $data['gong'],
                        'reason' => '增项修改工期',
                        'type' => 1,
                        'envelopes_id' => $data['envelopes_id']
                    ]
                );
                
                $envelopeRecords->record($array);
                
                \db('app_user_order', config('database.db2'))->where('order_id', $data['order_id'])->update(['plan_work_time' => ($data['gong'] + $envelopesFind['gong']) * 24 * 60 * 60]);
            }
            db()->commit();
            $this->pdf->put($data['order_id'], 1, 0);
            $this->inspect($data['order_id'], $data['envelopes_id']);
            sendOrder($data['order_id']);
            r_date($id, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /*
     * 基建签证单
     */
    public function VisaDetails(VisaForm $visaForm)
    {
        $data    = Authority::param(['order_id', 'autograph']);
        $VisaPng = $visaForm->VisaDetails($data['order_id'], $data['autograph']);
        r_date($VisaPng, 200);
        
    }
    
    /*
    * 修改报价清单
    */
    public function QuotationList(Capital $capital)
    {
        $data = Authority::param(['give_remarks', 'capital_id', 'class_b']);
        $capital->isUpdate(true)->save(['class_b' => $data['class_b'], 'projectRemark' => $data['give_remarks'], 'capital_id' => $data['capital_id']]);
        r_date(null, 200);
    }
    
    /*
    * 修改报价分组名称
    */
    public function QuotationListEdit(Capital $capital)
    {
        $data       = Authority::param(['capital_id', 'categoryName']);
        $capital_id = json_decode($data['capital_id'], true);
        $capital->whereIn('capital_id', $capital_id)->update(['categoryName' => $data['categoryName']]);
        r_date(null, 200);
    }
    
    /*
    * 修改公共项目标题备注
    */
    public function TitleRemarks(Envelopes $envelopes)
    {
        $data = Authority::param(['envelopes_id', 'project_title', 'give_remarks']);
        $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'project_title' => $data['project_title'], 'give_remarks' => $data['give_remarks']]);
        r_date(null, 200);
    }
    
    /*
    * 修改公共项目赠送
    */
    public function GiftItems(Envelopes $envelopes)
    {
        $data = Authority::param(['envelopes_id', 'give_b']);
        
        $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'give_b' => substr($data['give_b'], 0, -1)]);
        r_date(null, 200);
    }
    
    /*
    * 修改公共项目工期
    */
    public function GiftItemsGong(Envelopes $envelopes, EnvelopeRecords $envelopeRecords)
    {
        $data            = Authority::param(['envelopes_id', 'gong', 'reason']);
        $envelopesSingle = $envelopes->getFind($data['envelopes_id']);
        $aggregate       = [];
        
        array_push($aggregate, [
            'previous_quantity' => $envelopesSingle['gong'],
            'post_quantity' => $data['gong'],
            'type' => 1,
            'reason' => $data['reason'],
            'envelopes_id' => $data['envelopes_id']
        ]);
        if ($envelopesSingle['gong'] != $data['gong']) {
            $main_mode_type1 = db('sign')->where('order_id', $envelopesSingle['ordesr_id'])->field('autograph,confirm')->find();
            if ($main_mode_type1['confirm'] == 3 && empty($main_mode_type1['autograph'])) {
                db('sign')->where('order_id', $envelopesSingle['ordesr_id'])->delete();
            }
            $state = db('order')->where('order_id', $envelopesSingle['ordesr_id'])->value('state');
            if(!empty($main_mode_type1['autograph']) && $state==3){
                r_date(null, 300,'合同已签字不允许编辑');
            }
        }
        $envelopeRecords->record($aggregate);
        $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'gong' => $data['gong'], 'reason' => $data['reason']]);
        \db('app_user_order', config('database.db2'))->where('order_id', $envelopesSingle['ordesr_id'])->update(['plan_work_time' => $data['gong'] * 24 * 60 * 60]);
        sendOrder($envelopesSingle['ordesr_id']);
        r_date(null, 200);
    }
    
    /*
    * 修改报价清单
    */
    public function MarkCollaboration(Capital $capital)
    {
        
        $data = Authority::param(['cooperation', 'capital_id']);
        $capital->isUpdate(true)->save(['cooperation' => $data['cooperation'], 'capital_id', $data['capital_id']]);
        r_date(null, 200);
    }
    
    /**
     * 基检更新公共
     */
    public function AmountModification(Envelopes $envelopes, Capital $capital, EnvelopeRecords $envelopeRecords)
    {
        $data = Authority::param(['envelopes_id', 'purchasing_discount', 'purchasing_expense', 'give_money', 'expense']);
        db()->startTrans();
        try {
            
            $envelopesSingle = $envelopes->getFind($data['envelopes_id']);
            $capital         = $capital->where(['ordesr_id' => $envelopesSingle['ordesr_id'], 'types' => 1, 'enable' => 1])->select();
            $state = db('order')->where('order_id', $envelopesSingle['ordesr_id'])->value('state');
            $main_mode_type1 = db('sign')->where('order_id', $envelopesSingle['ordesr_id'])->field('autograph,confirm')->find();
            if ($main_mode_type1['confirm'] == 3 && empty($main_mode_type1['autograph']) && $state<4) {
                db('sign')->where('order_id', $data['order_ids'])->delete();
            }
            if(!empty($main_mode_type1['autograph']) && $state==3){
                throw new Exception('合同已签字不允许编辑');
            }
            $result       = [];
            $resultMain   = [];
            $resultAgency = [];
            foreach ($capital as $key => $info) {
                if ($info['agency'] == 0) {
                    $resultMain[] = $info;
                }
                if ($info['agency'] == 1) {
                    $resultAgency[] = $info;
                }
                $result[$info['agency']][] = $info;
            }
//            if (config('cityId') == 202) {
//                if (isset($resultMain) && !empty($resultMain)) {
//                    $cap = array_sum(array_column($resultMain, 'to_price'));
//                    if ($cap > 0) {
//                        if ((string)($cap * config('give_money')) < $data['give_money']) {
//                            throw  new  Exception('主合同优惠金额不能大于主合同订单总价的' . (config('give_money') * 100) . '%');
//                        }
//                        if ((string)($cap * config('expense')) > $data['expense']) {
//                            throw  new  Exception('主合同管理费不能小于主合同订单总价的' . (config('expense') * 100) . '%');
//                        }
//                    } else {
//                        if ($data['give_money'] != 0) {
//                            throw new Exception('主合同没有清单');
//                        }
//                        if ($data['expense'] != 0) {
//                            throw new Exception('主合同没有清单');
//                        }
//                    }
//
//                }
//                if (isset($resultAgency) && !empty($resultAgency)) {
//                    $cap1 = array_sum(array_column($resultAgency, 'to_price'));
//                    if ($cap1 > 0) {
//                        if ((string)($cap1 * config('purchasing_discount')) < $data['purchasing_discount']) {
//                            throw  new  Exception('代购优惠金额不能大于代购订单总价的' . (config('purchasing_discount') * 100) . '%');
//                        }
//                        if ((string)($cap1 * config('purchasing_expense')) > $data['purchasing_expense']) {
//                            throw  new  Exception('代购管理费不能小于代购订单总价的' . (config('purchasing_expense') * 100) . '%');
//                        }
//                    } else {
//                        if ($data['purchasing_discount'] != 0) {
//                            throw new Exception('代购合同没有清单');
//                        }
//                        if ($data['purchasing_expense'] != 0) {
//                            throw new Exception('主合同没有清单');
//                        }
//
//                    }
//                }
//            }
            
            
            $purchasing_discount = round($data['purchasing_discount'], 2) + round($envelopesSingle['purchasing_discount_money'], 2);
            $purchasing_expense  = round($data['purchasing_expense'], 2);
            $give_money          = round($data['give_money'], 2) + round($envelopesSingle['main_discount_money'], 2);
            $expense             = round($data['expense'], 2);
            $cli                 = new Client();
            if ($envelopesSingle['purchasing_discount'] != $purchasing_discount || $envelopesSingle['purchasing_expense'] != $purchasing_expense) {
                //（改变后的管理费-优惠）-（改变前的管理费-优惠）
                $moeny = ($purchasing_expense - $purchasing_discount) - ($envelopesSingle['purchasing_expense'] - $envelopesSingle['purchasing_discount']);
                $list  = json_encode(["order_id" => $envelopesSingle['ordesr_id'], "type" => 2, 'money' => $moeny]);
                $cli->index($list, $cli::order_queue, $cli::order_routingkey);
            }
            if ($envelopesSingle['give_money'] != $give_money || $envelopesSingle['expense'] != $expense) {
                $moeny = ($expense - $give_money) - ($envelopesSingle['expense'] - $envelopesSingle['give_money']);
                $list  = json_encode(["order_id" => $envelopesSingle['ordesr_id'], "type" => 1, 'money' => $moeny]);
                $cli->index($list, $cli::order_queue, $cli::order_routingkey);
            }
            $oi        = [
                'give_money' => $give_money,//优惠金额
                'purchasing_discount' => $purchasing_discount,
                'expense' => $expense,
                'purchasing_expense' => $purchasing_expense,
                'envelopes_id' => $data['envelopes_id']
            ];
            $aggregate = [];
            
            if ($envelopesSingle['purchasing_discount'] != $purchasing_discount) {
                array_push($aggregate, [
                    'previous_quantity' => $envelopesSingle['purchasing_discount'],
                    'post_quantity' => $purchasing_discount,
                    'type' => 2,
                    'reason' => '变更代购主材优惠金额',
                    'envelopes_id' => $data['envelopes_id']
                ]);
            }
            
            if ($envelopesSingle['purchasing_expense'] != $purchasing_expense) {
                array_push($aggregate, [
                    'previous_quantity' => $envelopesSingle['purchasing_expense'],
                    'post_quantity' => $purchasing_expense,
                    'type' => 2,
                    'reason' => '变更代购主材管理费',
                    'envelopes_id' => $data['envelopes_id']
                ]);
            }
            
            if ($envelopesSingle['give_money'] != $give_money) {
                array_push($aggregate, [
                    'previous_quantity' => $envelopesSingle['give_money'],
                    'post_quantity' => $give_money,
                    'type' => 2,
                    'reason' => '变更主材优惠金额',
                    'envelopes_id' => $data['envelopes_id']
                ]);
            }
            if ($envelopesSingle['expense'] != $expense) {
                array_push($aggregate, [
                    'previous_quantity' => $envelopesSingle['expense'],
                    'post_quantity' => $expense,
                    'type' => 2,
                    'reason' => '变更主材管理费',
                    'envelopes_id' => $data['envelopes_id']
                ]);
            }
            
            if (!empty($aggregate)) {
                
                $envelopeRecords->record($aggregate);
            }
            
            $envelopes->isUpdate(true)->save($oi);
            $main_mode_type1 = db('sign')->where('order_id', $envelopesSingle['ordesr_id'])->field('autograph,confirm')->find();
            if ($main_mode_type1['confirm'] == 3 && empty($main_mode_type1['autograph'])) {
                db('sign')->where('order_id', $envelopesSingle['ordesr_id'])->delete();
            }
            db()->commit();
            sendOrder($envelopesSingle['ordesr_id']);
            $this->pdf->put($envelopesSingle['ordesr_id'], 1, 0);
            r_date(null, 200);
            
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /*
     * 数据同步
     */
    public function DataMatching(DetailedOptionValue $detailedOptionValue, Common $common, Capital $capital)
    {
        $data = Authority::param(['projectJson']);
        
        $list = null;
        
        if (!empty(json_decode($data['projectJson'], true))) {
            $projectJson = json_decode($data['projectJson'], true);
            $list        = $detailedOptionValue->matching($projectJson);
            foreach ($list as $k => $l) {
                foreach ($l['data'] as $o => $v) {
                    $is_compose = db('detailed')->where('detailed_id', $v['projectId'])->value('display');
                    if ($is_compose == 1) {
                        if (!empty($v['specsList']) && $v['square'] != 0) {
                            $ValueId             = array_column($v['specsList'], 'option_value_id');
                            $CapitalPrice        = $common->newCapitalPrice($detailedOptionValue, $v['projectId'], $ValueId);
                            $CapitalPriceSection = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $v['square']);
                            if (!$CapitalPrice['code']) {
                                r_date(null, 300, $CapitalPrice['msg']);
                            }
                            
                            $list[$k]['data'][$o]['projectMoney'] = $CapitalPriceSection[3];
                            $list[$k]['data'][$o]['allMoney']     = $CapitalPriceSection[1];
                        }
                    } else {
                        unset($list[$k]['data'][$o]);
                        
                    }
                    
                    
                }
                
            }
            foreach ($list as $k => $l) {
                $po               = array_merge($l['data']);
                $list[$k]['data'] = $po;
            }
        }
        
        
        r_date($list, 200);
    }
    
    /*
     * 检查有没有代购
     */
    public function inspect($orderId, $envelopes_id)
    {
        $capitals = (new  capital)->whetherAgency(['ordesr_id' => $orderId, 'types' => 1, 'enable' => 1, 'agency' => 1]);
        if ($capitals > 0) {
            $listOrderType = 1;
        } else {
            $listOrderType = 0;
            (new envelopes)->isUpdate(true)->save(['envelopes_id' => $envelopes_id, 'purchasing_discount' => 0, 'purchasing_expense' => 0]);
        }
        $capitals = (new  capital)->whetherAgency(['ordesr_id' => $orderId, 'types' => 1, 'enable' => 1, 'agency' => 0]);
        if ($capitals == 0) {
            (new envelopes)->isUpdate(true)->save(['envelopes_id' => $envelopes_id, 'expense' => 0, 'give_money' => 0]);
        }
        (new orderModel)->orderAgency(['order_id' => $orderId, 'order_agency' => $listOrderType]);
    }
    
    /*
     * 预计工时查看
     */
    public function hoursView(Common $common, DetailedOptionValue $detailedOptionValue)
    {
        
        $data        = Authority::param(['envelopes_id', 'projects']);
        $capitalList = json_decode($data['projects'], true);
        
        $capitalArray = [];
        foreach ($capitalList as $k => $list) {
            if ($list['agency'] == 0) {
                if (isset($list['specsList'])) {
                    $ValueId = array_column($list['specsList'], 'option_value_id');
                } else {
                    $ValueId = [];
                }
                
                
                $sum = $common->newCapitalPrice($detailedOptionValue, $list['projectId'], $ValueId);
                
                if (!$sum['code']) {
                    r_date(null, 300, $sum['msg']);
                }
                $capitalArray['main'][$k]['categoryTitle'] = $sum['data']['categoryTitle'];
                $capitalArray['main'][$k]['work_time']     = $sum['data']['sumTime'] * $list['square'];
                
                if (!empty($sum['data']['work_time'])) {
                    foreach ($sum['data']['work_time'] as $item) {
                        if ($item->begin <= $list['square'] && $item->end > $list['square']) {
                            if ($capitalArray['main'][$k]['work_time'] * $item->value != 0) {
                                $capitalArray['main'][$k]['work_time'] = $capitalArray['main'][$k]['work_time'] * $item->value;
                                
                            }
                            
                        }
                    }
                }
            }
            if ($list['agency'] == 1) {
                $capitalArray['purchasing'][$k]['categoryTitle'] = $list['projectTitle'];
                $detailed                                        = db('detailed')->where('detailed_id', $list['projectId'])->field('detailed.delivery_period_days_1,detailed.delivery_period_days_2')->find();
                $capitalArray['purchasing'][$k]['work_time']     = empty($detailed['delivery_period_days_1']) ? '预计0天' : '预计' . $detailed['delivery_period_days_1'] . '~' . $detailed['delivery_period_days_2'] . '天';
                $capitalArray['purchasing'][$k]['maxTime']       = $detailed['delivery_period_days_2'];
            }
            
            
        }
        
        $main = [];
        if (!empty($capitalArray['main'])) {
            $main = array_unique(array_column($capitalArray['main'], 'categoryTitle'));
        }
        $purchasingList = [];
        $mainList       = [];
        $Sum            = 0;
        
        foreach ($main as $k => $value) {
            $datas = [];
            
            foreach ($capitalArray['main'] as $item) {
                if ($value == $item['categoryTitle']) {
                    $datas[] = $item['work_time'];
                }
                
            }
            $mainList[$k]['title'] = $value;
            $mainList[$k]['data']  = $datas;
            
            $mainList[$k]['sum'] = ceil(array_sum($datas) / 9);
            $Sum                 += $mainList[$k]['sum'];
        }
        $max = [];
        if (!empty($capitalArray['purchasing'])) {
            foreach ($capitalArray['purchasing'] as $y => $item) {
                $purchasingList[$y]['title'] = $item['categoryTitle'];
                $purchasingList[$y]['datas'] = $item['work_time'];
                $purchasingList[$y]['data']  = $item['maxTime'];
                $max[]                       = empty($item['maxTime']) ? 0 : $item['maxTime'];
            }
        }
        
        
        r_date(['main' => ['mainData' => empty($mainList) ? null : array_merge($mainList), 'mainSum' => $Sum], 'purchasing' => ['purchasingData' => empty($purchasingList) ? null : array_merge($purchasingList), 'purchasingListSum' => empty($max) ? 0 : max(array_unique($max))]], 200);
    }
    
    /*
     * 优惠券
     */
    public function coupon(Common $common)
    {
        
        $data = Authority::param(['orderId']);
        $list = $common->coupon($data['orderId']);
        r_date($list, 200);
        
    }
    
    /*
     * 修改优惠卷
     */
    public function ModifyCoupon(Envelopes $envelopes)
    {
        $data = Authority::param(['envelopes_id', 'id', 'give_b']);
        
        $envelopes = $envelopes->with(['CapitalList', 'CapitalList.specsList', 'OrderList'])
            ->where(['envelopes_id' => $data['envelopes_id']])
            ->find()->toArray();
        
        $agency      = [];
        $sumlist     = [];
        $capitalList = $envelopes['capital_list'];
        foreach ($capitalList as $k => $item) {
            if ($item['agency'] == 1) {
                $agency[] = $item;
            } else {
                $sumlist[] = $item;
            }
        }
        $agencysum = round(array_sum(array_column($agency, 'allMoney')), 2);
        $sumlist   = round(array_sum(array_column($sumlist, 'allMoney')), 2);
        db()->startTrans();
        try {
            
            if (!empty($envelopes['main_id'])) {
                $coupon_user = db('coupon_user', config('database.zong'))->where('id', $envelopes['main_id'])->find();
                if ($coupon_user['usage_status'] == 2) {
                    throw new Exception('优惠卷已使用不能更改');
                }
            }
            if (!empty($envelopes['purchasing_id'])) {
                $coupon_users = db('coupon_user', config('database.zong'))->where('id', $envelopes['purchasing_id'])->find();
                if ($coupon_users['usage_status'] == 2) {
                    throw new Exception('优惠卷已使用不能更改');
                }
            }
            if ($data['id'] != 0) {
                $coupon = db('coupon_user', config('database.zong'))->join('coupon', 'coupon_user.coupon_id=coupon.id', 'left')->field('coupon_user.id,coupon.coupon_use_type,coupon.coupon_limit,coupon.coupon_amount,coupon.coupon_type,coupon.coupon_discount,coupon.coupon_prize_title')->whereIn('coupon_user.id', $data['id'])->select();
                
                $coupon_user_id            = 0;
                $coupon_discount           = 0;
                $purchasing_discount_money = 0;
                $purchasing_id             = 0;
                foreach ($coupon as $list) {
                    
                    if ($list['coupon_use_type'] == 1) {
                        
                        if ($list['coupon_type'] == 1) {
                            if ($sumlist <= ($list['coupon_limit'] / 100)) {
                                throw new Exception('未达到使用门槛');
                            }
                            $coupon_discount += ($list['coupon_amount'] / 100);
                        }
                        
                        if ($list['coupon_type'] == 2) {
                            $coupon_discount += $sumlist * (1 - ($list['coupon_discount'] / 100));
                        }

//                        if ($list['coupon_type'] == 3) {
//                            $data['give_a'] .= $list['coupon_prize_title'] . ',';
//                        }
                        $coupon_user_id = $list['id'];
                    }
                    if ($list['coupon_use_type'] == 2) {
                        if ($agencysum <= ($list['coupon_limit'] / 100)) {
                            throw new Exception('未达到使用门槛');
                        }
                        $purchasing_discount_money += ($list['coupon_amount'] / 100);
                        if ($list['coupon_type'] == 2) {
                            $purchasing_discount_money += $agencysum * (1 - ($list['coupon_discount'] / 100));
                        }
                        $purchasing_id = $list['id'];
//                        if ($list['coupon_type'] == 3) {
//                            $data['give_a'] .= $list['coupon_prize_title'] . ',';
//                        }
                    }
                    
                    
                }
                
                if ($coupon_discount != 0) {
                    $coupon_discount                 = round($coupon_discount, 2);
                    $datalist['main_discount_money'] = $coupon_discount;
                    $datalist['give_money']          = $envelopes['give_money'] - $envelopes['main_discount_money'] + $coupon_discount;
                    $datalist['main_id']             = $coupon_user_id;
                }
                if ($purchasing_discount_money != 0) {
                    $purchasing_discount_money             = round($purchasing_discount_money, 2);
                    $datalist['purchasing_discount_money'] = $purchasing_discount_money;
                    $datalist['purchasing_discount']       = $envelopes['purchasing_discount'] - $envelopes['purchasing_discount_money'] + $purchasing_discount_money;
                    $datalist['purchasing_id']             = $purchasing_id;
                    
                }
                if ($coupon_discount == 0 && $envelopes['main_discount_money'] != 0) {
                    $datalist['main_discount_money'] = $coupon_discount;
                    $datalist['give_money']          = $envelopes['give_money'] - $envelopes['main_discount_money'];
                    
                }
                if ($purchasing_discount_money != 0 && $envelopes['purchasing_discount_money'] != 0) {
                    $datalist['purchasing_discount_money'] = $purchasing_discount_money;
                    $datalist['purchasing_discount']       = $envelopes['purchasing_discount'] - $envelopes['purchasing_discount_money'];
                    
                }
                if (!empty($data['give_b'])) {
                    $datalist['give_b']  = substr($data['give_b'], 0, -1);
                    $datalist['main_id'] = $coupon_user_id;
                }
            } else {
                if ($envelopes['main_discount_money'] != 0) {
                    $datalist['give_money']          = $envelopes['give_money'] - $envelopes['main_discount_money'];
                    $datalist['main_discount_money'] = 0;
                    $datalist['main_id']             = 0;
                }
                if ($envelopes['purchasing_discount_money'] != 0) {
                    $datalist['purchasing_discount']       = $envelopes['purchasing_discount'] - $envelopes['purchasing_discount_money'];
                    $datalist['purchasing_discount_money'] = 0;
                    $datalist['purchasing_id']             = 0;
                }
                
                if (empty($data['give_b']) || !empty($data['give_b'])) {
                    
                    $datalist['give_b']  = $data['give_b'];
                    $datalist['main_id'] = 0;
                }
            }
            \db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update($datalist);
            db()->commit();
            sendOrder($envelopes['ordesr_id']);
            r_date(null, 200);
            
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /*
     * 优惠卷重新计算价格
     */
    public function CouponCalculation($envelopes_id, $amount, $agentSum, $types = 0, $capital_id = 0)
    {
        $envelopesObject = new  Envelopes();
        $envelopes       = $envelopesObject->with(['CapitalList', 'CapitalList.specsList', 'OrderList'])
            ->where(['envelopes_id' => $envelopes_id])
            ->find()->toArray();
        
        $agency      = [];
        $sumlist     = [];
        $capitalsum  = [];
        $datalist=[];
        $coupon      = null;
        $capitalList = $envelopes['capital_list'];
        
        foreach ($capitalList as $k => $item) {
            if ($item['agency'] == 1) {
                $agency[] = $item;
            }
            if ($item['agency'] == 0) {
                $sumlist[] = $item;
            }
            if ($item['capital_id'] == $capital_id) {
                $capitalsum[] = $item;
            }
        }
        if ($types == 1) {
            if (!empty($capital_id)) {
                $SumCapital = round(array_sum(array_column($capitalsum, 'allMoney')), 2);
                $agencysum  = round(array_sum(array_column($agency, 'allMoney')), 2) - $SumCapital + $agentSum;
                $sumlist    = round(array_sum(array_column($sumlist, 'allMoney')), 2) - $SumCapital + $amount;
            } else {
                $agencysum = round(array_sum(array_column($agency, 'allMoney')), 2) - $agentSum;
                $sumlist   = round(array_sum(array_column($sumlist, 'allMoney')), 2) - $amount;
            }
            
        } else {
            $agencysum = round(array_sum(array_column($agency, 'allMoney')), 2) + $agentSum;
            $sumlist   = round(array_sum(array_column($sumlist, 'allMoney')), 2) + $amount;
        }
        
        if (!empty($envelopes['main_id'])) {
            $coupon = db('coupon_user', config('database.zong'))->join('coupon', 'coupon_user.coupon_id=coupon.id', 'left')->where('coupon_user.id', $envelopes['main_id'])->field('coupon_user.id,coupon.coupon_use_type,coupon.coupon_limit,coupon.coupon_amount,coupon.coupon_type,coupon.coupon_discount,coupon.coupon_prize_title')->find();
        }
        if (!empty($envelopes['purchasing_id'])) {
            $coupon1 = db('coupon_user', config('database.zong'))->join('coupon', 'coupon_user.coupon_id=coupon.id', 'left')->where('coupon_user.id', $envelopes['purchasing_id'])->field('coupon_user.id,coupon.coupon_use_type,coupon.coupon_limit,coupon.coupon_amount,coupon.coupon_type,coupon.coupon_discount,coupon.coupon_prize_title')->find();
        }
        $coupon_user_id            = 0;
        $coupon_discount           = 0;
        $purchasing_discount_money = 0;
        $purchasing_id             = 0;
        
        
        if (!empty($coupon)) {
            if ($coupon['coupon_type'] == 1) {
                if ($sumlist < ($coupon['coupon_limit'] / 100)) {
                    throw new Exception('未达到使用门槛');
                }
                $coupon_discount += ($coupon['coupon_amount'] / 100);
            }
            
        }
        if (!empty($coupon1)) {
            if ($coupon1['coupon_type'] == 2) {
                if ($agencysum < ($coupon1['coupon_limit'] / 100)) {
                    throw new Exception('未达到使用门槛');
                }
                $purchasing_discount_money += $agencysum * (1 - ($coupon1['coupon_discount'] / 100));
            }
            
        }
        if ($coupon_discount != 0) {
            $datalist['main_discount_money'] = $coupon_discount;
            $datalist['give_money']          = $envelopes['give_money'] - $envelopes['main_discount_money'] + $coupon_discount;
            
        }
        if ($purchasing_discount_money != 0) {
            
            $datalist['purchasing_discount_money'] = $purchasing_discount_money;
            $datalist['purchasing_discount']       = $envelopes['purchasing_discount'] - $envelopes['purchasing_discount_money'] + $purchasing_discount_money;
            
        }
        if ($coupon['coupon_type'] != 3 ) {
            if(!empty($coupon1)  && !empty($datalist)){
                \db('envelopes')->where('envelopes_id', $envelopes_id)->update($datalist);
            }
            if(!empty($coupon) && !empty($datalist)){
                \db('envelopes')->where('envelopes_id', $envelopes_id)->update($datalist);
            }
           
        }
        
        
    }
    
}